#include <iostream>
#include <pthread.h>
#include <unistd.h>
 
// 互斥锁
pthread_mutex_t glock = PTHREAD_MUTEX_INITIALIZER;
// 同步
pthread_cond_t acond,bcond;
int ret = 0;
 
void *active1(void *args)
{
    while(1)
    {
        pthread_mutex_lock(&glock);
        while(ret == 1){
            pthread_cond_wait(&acond, &glock);
        }
        printf("线程A打印--我是线程A\n");
        ret++;
        pthread_mutex_unlock(&glock);
        pthread_cond_signal(&bcond); // 唤醒 b 线程
    }
}
 
void *active2(void *args)
{
    while(1)
    {
        sleep(1);
        pthread_mutex_lock(&glock);
        while(ret == 0){
            pthread_cond_wait(&bcond, &glock);
        }
        printf("线程B打印--我是线程B\n");
        ret--;
        pthread_mutex_unlock(&glock);
        pthread_cond_signal(&acond); // 唤醒 a 线程
    }
}
int main()
{
    pthread_cond_init(&acond, nullptr);
    pthread_cond_init(&bcond, nullptr);
 
    pthread_t tid_a, tid_b;
 
    int t = pthread_create(&tid_a, nullptr, active1, (void*)("thread-A"));
    
    if(t < 0){
        perror("pthread_threadA");
        return 0;
    }
 
    t = pthread_create(&tid_b, nullptr, active2, (void*)("thread-B"));
    if(t < 0){
        perror("pthread_threadA");
        return 0;
    }
 
    pthread_join(tid_a, nullptr);
    pthread_join(tid_b, nullptr);
 
    pthread_mutex_destroy(&glock);
    pthread_cond_destroy(&acond);
    pthread_cond_destroy(&bcond);
 
    return 0;
}
 